import { _decorator } from 'cc';
import { app } from '../../../../app-core/App';
import { Logger } from '../../../../app-core/common/log/Logger';
import { BasePresenter } from '../../../../app-core/mvp/base/BasePresenter';
import { ILoadingPresenter, ILoadingView } from '../contract/LoadingContract';

const { ccclass, property } = _decorator;

@ccclass('LoadingPresenter')
export default class LoadingPresenter extends BasePresenter<ILoadingView> implements ILoadingPresenter {

    onAttach(): void {

    }
    onDetach(): void {

    }

    public startLoading(progress: (cur: number, total: number) => void, complete: (total: number) => void) {
        const totalAsset = 12;
        let completeAsset = 0;

        const onProgress = function (next) {
            return function () {
                //  todo init res
                // 


                progress && progress(++completeAsset, totalAsset);
                // next();

                setTimeout(next, 100);
            }
        }

        const onLoading = function (resid: Number, finish: Function) {
            Logger.debug("===== loading the resourse, id = " + resid);
            finish();
            // setTimeout(finish, 1000);
        }

        const async1 = app.task.createSync();
        let testResList: Array<Number> = [1, 2, 3, 4, 5, 6];
        testResList.forEach((resid) => {
            async1.add((next) => {
                onLoading(resid, onProgress(next));
            })
        });

        // const async2 = this.task.createSync();
        let testResList2: Array<Number> = [10, 20, 30, 40, 50, 60];
        testResList2.forEach((resid) => {
            async1.add((next) => {
                onLoading(resid, onProgress(next));
            })
        });

        async1.add((next) => {
            // this.loader.loadDir('Icon', SpriteFrame, (finished: number, total: number, item: AssetManager.RequestItem) =>{
            //     progress && progress(finished, total);

            // }, (err: Error | null, data: Asset) => {
            //     if (err) {
            //         Logger.error(err);
            //     }

            //     next();
            // })

            next();
        })

        // const sync = this.task.createSync();
        // sync.add((next) => {
        //     async1.start(next)
        // });

        // sync.add((next) => {
        //     async2.start(next)
        // });

        async1.start(() => {
            Logger.debug('=====================================>>>>>> complete....');
            complete && complete(totalAsset);
        })
    }
}